import React, { useEffect, useState } from "react";
import { Link, Switch, Route } from "react-router-dom";

// let timer;

const getData = () => {
  return fetch("http://www.pudge.wang:3080/api/rated/list")
    .then((response) => response.json())
    .then((res) => {
      return res;
    });
};

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(10);
  const handleClick = () => {
    setCount((v) => v + 1);
  };
  const handleClick2 = () => {
    setNum((v) => v + 1);
  };
  // useEffect是用来代替生命周期的
  // 里面可以传入一个回调函数, 第二个参数是一个数组(依赖)

  // 如果里面只传入第一参数，相当于componentDidMount以及componentDidUpdate
  // 如果有第二个参数，相当于componentDidMount
  // 如果第二个参数有内容，相当于vue里面的watch
  // 如果在回调函数里面，return一个函数，相当于componentWillUnmount
  useEffect(() => {
    console.log(count);
  }, [count]);

  // useEffect(() => {
  //   const timer = setInterval(() => {
  //     console.log(123);
  //   }, 1000);
  //   return () => {
  //     console.log("unMount");
  //     clearInterval(timer);
  //   };
  // }, []);

  useEffect(() => {
    // 如果在useEffect里面要调用封装好的请求，需要写成自执行函数
    (async () => {
      const res = await getData();
      console.log(res);
    })();
  }, []);

  return (
    <>
      <h2>useEffect</h2>
      <p>count: {count}</p>
      <button onClick={handleClick}>btn</button>
      <p>num: {num}</p>
      <button onClick={handleClick2}>btn2</button>
    </>
  );
};

const About = () => {
  return <div>about页面</div>;
};

const App2 = () => {
  return (
    <>
      <ul>
        <li>
          <Link to="/app">app</Link>
        </li>
        <li>
          <Link to="/about">about</Link>
        </li>
      </ul>

      <Switch>
        <Route path="/app">
          <App />
        </Route>
        <Route path="/about">
          <About />
        </Route>
      </Switch>
    </>
  );
};

export default App2;
